import dva from 'dva';
import {userSearch} from '../services/user';
import Cookies from 'js-cookie';
import {routerRedux} from 'dva/router';

export default {
  namespace: 'login',
  state: {
    list: [],
  },
  reducers: {
    save(state, {payload: {data: list}}) {
      return {...state, list};
    },
  },
  effects: {
    *login({payload: {page}}, {call, put}) {
      const {data} = yield call(userSearch, {page});
      yield put({type: 'save', payload: {data: data.list}});
    }
  },
  subscriptions: {
    setup({dispatch, history}) {
      return history.listen(({pathname, query}) => {
        if (pathname === '/login') {
          if (Cookies.hasItem('token')) {
            routerRedux.push('/users');
          } else {
            // dispatch({type: 'login', payload: query});
          }
        }
      });
    }
  }
};
